import { styled } from "@umijs/max"
import { useRequest } from "ahooks"
import { Button, Card, Descriptions, Modal, Select, Space, Table } from "antd"
import { AppUserStatus, queryCarList, getUserDetail } from "./services"
import { useEffect, useMemo, useState } from "react"
import { CouponCutType, CouponInfoType, queryUserCouponList } from "@/pages/coupon/couponList/services"
import { MoneyCard, queryMoneyCardList, queryDealRecordList } from "@/pages/coupon/cardList/services"
import { DealRecordTable } from "./components/DealRecordModal"
import { history } from '@umijs/max'
import { enum2options } from "@/utils/enum2options"
import dayjs from "dayjs"
import { jump2target } from "@/utils/common"

const Container = styled.div`
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 24px;

  .ant-descriptions-item-label {
    align-items: center !important;
  }
`

export enum UserCouponStatus {
  未使用 = 1,
  已使用 = 2,
  已失效 = 3,
}
export enum UserMoneyCardStatus {
  可使用 = 1,
  已失效 = 3,
}

const AppUserDetail: React.FC<RoutePageProps> = (props) => {
  const { run, data } = useRequest(getUserDetail, {manual: true})
  const carList = useRequest(queryCarList, {manual: true})
  const userCouponList = useRequest(queryUserCouponList, {manual: true})
  const cardList = useRequest(queryMoneyCardList, {manual: true})
  const dealRecordList = useRequest(queryDealRecordList, {manual: true})
  const [couponStatus, setCouponStatus] = useState<UserCouponStatus>()
  const [moneyCardStatus, setMoneyCardStatus] = useState<UserMoneyCardStatus>()
  const [dealRecordOpen, setDealRecordOpen] = useState(false)

  const openOrgDetail = (orgId: number) => {
    jump2target(`/station/org/detail?type=detail&id=${orgId || ''}`, {needRefresh: true})
    sessionStorage.setItem('__/station/org/detail_title', '经销商详情')
  }

  const searchCarList = (pageNum: number, pageSize: number) => {
    carList.run({
      userId: props.params.userId,
      pageNum, pageSize,
    })
  }

  const openDealRecordModal = (id: string) => {
    setDealRecordOpen(true)
    dealRecordList.run({
      infoId: id,
      userId: props.params.userId,
      pageNum: 1,
      pageSize: 100,
    })
  }

  const searchCouponList = (pageNum: number, pageSize: number) => {
    userCouponList.run({
      userId: props.params.userId,
      pageNum, pageSize,
      status: couponStatus,
    })
  }

  const searchMoneyCardList = (pageNum: number, pageSize: number) => {
    cardList.run({
      userId: props.params.userId,
      pageNum, pageSize,
      status: moneyCardStatus,
    })
  }

  const items = useMemo(() => {
    if (!data?.data) return []
    const result = []
    result.push(
      {key: 'userImg', label: '用户头像', children: <img style={{width: 40, height: 40}} src={data?.data.userImg} />},
      {key: 'nickname', label: '用户昵称', children: <div style={{height: 40, display: 'flex', alignItems: 'center'}}>{data?.data.nickname}</div>},
      {key: 'telephone', label: '用户手机号', children: <div style={{height: 40, display: 'flex', alignItems: 'center'}}>{data?.data.telephone}</div>},
    )
    if (data?.data.orgId) {
      result.push({key: 'orgId', label: '是否经销商', children: <a onClick={() => openOrgDetail(data?.data.orgId)}>查看</a>})
    }
    result.push(
      {key: 'companyStatus', label: '是否企业员工', children: data?.data.companyStatus === 1 ? '是' : '否'}, 
      {key: 'personMoney', label: '个人余额(元)', children: data?.data.personMoney}, 
    )
    if (data?.data.companyStatus === 1) {
      result.push({key: 'companyMoney', label: '企业余额(元)', children: data?.data.companyMoney})
    }
    result.push(
      {key: 'power', label: '用电量(度)', children: data?.data.power},
      {key: 'totalMoney', label: '充电费用(元)', children: data?.data.totalMoney},
      {key: 'status', label: '状态', children: AppUserStatus[data?.data.status]},
    )
    return result
  }, [data])

  const onCancel = () => {
    setDealRecordOpen(false)
    dealRecordList.mutate(undefined)
  }

  useEffect(() => {
    const { userId } = props.params
    if (userId) {
      run({userId})
      searchCarList(1, 10)
      searchCouponList(1, 10)
      searchMoneyCardList(1, 10)
    }
    const refresh = () => {
      run({userId})
      searchCarList(1, 10)
      searchCouponList(1, 10)
      searchMoneyCardList(1, 10)
    }
    window.addEventListener('refreshAppUserDetail', refresh)
    return () => {
      window.removeEventListener('refreshAppUserDetail', refresh)
    }
  }, [props.params.userId])

  return (
    <Container>
      <Card title='用户信息'>
        <Descriptions 
          items={items}
        />
      </Card>
      <Card title='车辆列表' extra={<Space>
        <Button type="primary" onClick={() => searchCarList(1, 10)}>查询</Button>
      </Space>}>
        <Table
          rowKey='id'
          loading={carList.loading}
          dataSource={carList.data?.data}
          pagination={{
            pageSize: 10,
            total: carList.data?.data.length || 0,
            simple: true,
            size: 'small',
            hideOnSinglePage: true,
            onChange: searchCarList,
          }}
          columns={[
            {title: '车牌号', dataIndex: 'carPlat', width: 100},
            {title: '车品牌', dataIndex: 'carBrand', width: 100},
            {title: '车型号', dataIndex: 'carModel', width: 100},
            {title: '车系列', dataIndex: 'carSeries', width: 100},
            {title: 'vin码', dataIndex: 'vin', width: 100},
            {title: '即插即充', dataIndex: 'vinStatus', width: 100, render: val => val === 2 ? '开启' : '关闭'},
            {title: '创建时间', dataIndex: 'createTime', width: 140, render: val => dayjs(val).format('YYYY-MM-DD')},
          ]}
        />
      </Card>
      <Card title='优惠券' extra={<Space>
        <span>状态: </span>
        <Select
          placeholder='请选择'
          options={enum2options(UserCouponStatus)}
          style={{width: 120}}
          value={couponStatus}
          onChange={setCouponStatus}
        />
        <Button type="primary" onClick={() => searchCouponList(1, 10)}>查询</Button>
      </Space>}>
        <Table
          rowKey='id'
          loading={userCouponList.loading}
          dataSource={userCouponList.data?.data}
          pagination={{
            pageSize: 10,
            total: userCouponList.data?.data.length || 0,
            simple: true,
            size: 'small',
            hideOnSinglePage: true,
            onChange: searchCouponList,
          }}
          columns={[
            {title: '券名称', dataIndex: 'title', width: 100},
            {
              title: '券类型',
              dataIndex: 'infoType',
              width: 100,
              render: val => val && CouponInfoType[val],
            },
            {title: '券内容', dataIndex: 'getM', width: 100, render: (val, record) => {
              if (record.infoType === CouponInfoType.折扣券) return `${val}折`
              return `减${val}元`
            }},
            {title: '优惠项目', dataIndex: 'cutType', width: 120, render: val => {
              return val && CouponCutType[val]
            }},
            {title: '使用范围', dataIndex: 'station', width: 120, render: val => {
              return val === 2 ? '部分场站' : '全部自营场站'
            }},
            {title: '状态', dataIndex: 'status', width: 100, render: val => val ? UserCouponStatus[val] : '--'}
          ]}
        />
      </Card>
      <Card title='现金卡' extra={<Space>
        <span>状态: </span>
        <Select
          placeholder='请选择'
          options={enum2options(UserMoneyCardStatus)}
          style={{width: 120}}
          value={moneyCardStatus}
          onChange={setMoneyCardStatus}
        />
        <Button type="primary" onClick={() => searchMoneyCardList(1, 10)}>查询</Button>
      </Space>}>
        <Table<MoneyCard>
          rowKey='id'
          loading={cardList.loading}
          dataSource={cardList.data?.data}
          pagination={{
            pageSize: 10,
            total: cardList.data?.data.length || 0,
            simple: true,
            size: 'small',
            hideOnSinglePage: true,
            onChange: searchMoneyCardList,
          }}
          columns={[
            {title: '卡标题', dataIndex: 'title', width: 140},
            {title: '兑换码', dataIndex: 'cardCode', width: 140},
            {title: '已使用金额(元)', dataIndex: 'cutMoney', width: 160},
            {title: '卡面额(元)', dataIndex: 'fullMoney', width: 140},
            {title: '状态', dataIndex: 'status', width: 100, render: val => val ? UserMoneyCardStatus[val] : '--'},
            {title: '操作', dataIndex: 'id', width: 100, render: val => {
              return <a onClick={() => openDealRecordModal(val)}>交易记录</a>
            }}
          ]}
        />
      </Card>
      <Card title='交易记录'>
        <DealRecordTable userId={data?.data.id} />
      </Card>
      <Modal
        open={dealRecordOpen}
        title='交易记录'
        onCancel={onCancel}
        okButtonProps={{hidden: true}}
        cancelText='关闭'
        width={1000}
      >
        <Table
          rowKey='id'
          loading={dealRecordList.loading}
          dataSource={dealRecordList.data?.data}
          pagination={{
            pageSize: 10,
            total: dealRecordList.data?.data.length || 0,
            simple: true,
            size: 'small',
            hideOnSinglePage: true,
          }}
          columns={[
            {title: '订单ID', dataIndex: 'orderId', width: 140},
            {title: '交易类型', dataIndex: 'infoType', width: 140, render: val => {
              if (val === 1) return '充电扣款'
              if (val === 2) return '占位扣款'
              return '--'
            }},
            {title: '付款金额', dataIndex: 'infoMoney', width: 140},
            {title: '付款时间', dataIndex: 'createTime', width: 140, render: val => {
              return dayjs(val).format('YYYY-MM-DD HH:mm:ss')
            }},
          ]}
        />
      </Modal>
    </Container>
  )
}

export default AppUserDetail
